package com.piece.core.framework.util.location;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.net.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 地理位置工具类
 */
@Slf4j
public class LocationUtil {

    // 赤道半径
    private static final double EARTH_RADIUS = 6378137;

    /**
     * 计算半径
     */
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据经纬度获取两点的距离(单位米)
     */
    public static Double getDistance(double lon1, double lat1, double lon2, double lat2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lon1) - rad(lon2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        return s;
    }

    /**
     * 根据经纬度获取两点的距离(单位米)
     */
    public static Double getDistance(BigDecimal lon1, BigDecimal lat1, BigDecimal lon2, BigDecimal lat2) {
        return getDistance(lon1.doubleValue(), lat1.doubleValue(), lon2.doubleValue(), lat2.doubleValue());
    }

    /**
     * 根据地址获取坐标
     *
     * @param url     地图API地址
     * @param key     地图API key
     * @param address 地址
     * @param city    城市
     */
    public static Map<String, Object> getCoordinateByAddress(String url, String key, String address, String city) {
        Map<String, Object> map = new HashMap();

        try {
            url = MessageFormat.format(url, key, URLEncoder.encode(address, "UTF-8"), URLEncoder.encode(city, "UTF-8"));
            AjaxResponse result = HttpUtil.get(url).execute().response();
            if (result.isSuccess()) {
                JSONObject jsonObject = JSON.parseObject(Convert.toStr(result.getParam(), ""));
                JSONArray array = (JSONArray) jsonObject.get("pois");
                if (array.size() > 0) {
                    JSONObject object = (JSONObject) array.get(0);
                    String location = object.getString("location");
                    String[] locs = location.split(",");
                    map.put("xIndex", locs[0]);
                    map.put("yIndex", locs[1]);
                }
            }
        } catch (Exception e) {
            log.error("获取地址坐标异常：{}", e.getMessage());
        }
        return map;
    }
}
